import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_member/bottom_navigation/botton_navigation_widget.dart';
import 'package:flutter_member/stytle/SvgImg.dart';
import 'package:flutter_member/widget/GoCustomPainterWidget.dart';
import 'package:flutter_member/widget/login_textinput_widget.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:parse_server_sdk/parse_server_sdk.dart';
import 'package:toast/toast.dart';

////登录主页面
class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  // 电话号码登录
  bool _phone = false;

  // 登录中状态
  bool _isLoading = false;

  ///手机号码
  TextEditingController _phoneController =
  TextEditingController(text: "63233020");

  /// 验证码
  TextEditingController _codeController = TextEditingController();

  /// 获取验证码返回的id
  var requestId = "";

  Timer _countdownTimer;
  DateTime _lastPressedAt; //上次点击时间
  /// 獲取驗證碼按鈕文字
  String _codeCountdownStr = '發送短信\n驗證碼';
  int _countdownNum = 59;
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>(); //用于检查输入框是否为空
  void reGetCountdown() {
    setState(() {
      if (_countdownTimer != null) {
        return;
      }
      _codeCountdownStr = '等待${_countdownNum--}再點\n擊發送';
      _countdownTimer = new Timer.periodic(new Duration(seconds: 1), (timer) {
        setState(() {
          if (_countdownNum > 0) {
            _codeCountdownStr = '${_countdownNum--}重新獲取';
          } else {
            _codeCountdownStr = '發送短信\n驗證碼';
            _countdownNum = 59;
            _countdownTimer.cancel();
            _countdownTimer = null;
          }
        });
      });
    });
  }

  @override
  void dispose() {
    _countdownTimer?.cancel();
    _countdownTimer = null;
    super.dispose();
  }

  /// 获得验证码
  Future<void> GetVerificationCode() async {
    reGetCountdown();
    final ParseCloudFunction function = ParseCloudFunction('smsShortCode');

    final Map<String, String> params = <String, String>{
      'phoneNumber': _phoneController.text,
      'callingCode': "853",
      'action': "login"
    };
    ParseResponse result = await function.execute(parameters: params);
    if (result.success) {
      setState(() {
        print(result.result);
        requestId = result.result;
      });
    }
  }

  Future<void> _login() async {
    setState(() => _isLoading = true);
    ParseResponse response;
    try {
      response = await ParseUser.loginWith("sms", {
        "id": "+853-" + _phoneController.text,
        "requestId": requestId,
        "code": _codeController.text
      });
      setState(() {
        _isLoading = false;
        switch (response.statusCode) {
          case 200:
            Navigator.of(context).pushAndRemoveUntil(
                MaterialPageRoute(
                    builder: (context) => BottomNavigationWidget(
                      indexState: 0,
                    )),
                    (route) => route == null);
            break;
          case 1:
            Toast.show("帳號錯誤", context,
                duration: Toast.LENGTH_SHORT, gravity: Toast.CENTER);
            break;
          case 101:
            Toast.show("密碼錯誤", context,
                duration: Toast.LENGTH_SHORT, gravity: Toast.CENTER);
            break;
          case 142:
            Toast.show("密碼錯誤", context,
                duration: Toast.LENGTH_SHORT, gravity: Toast.CENTER);
            break;
          case -1:
            Toast.show("服務器連接異常", context,
                duration: Toast.LENGTH_SHORT, gravity: Toast.CENTER);
            break;
        }
      });
    } catch (e) {}
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, designSize: Size(375, 667), allowFontScaling: false);
    return Scaffold(
      resizeToAvoidBottomPadding: true,
      body: SingleChildScrollView(
        child: Container(
            color: Color(0Xffffffff),
            height: MediaQuery.of(context).size.height,
            alignment: Alignment.center,
            child: Stack(
              children: <Widget>[
                CustomPaintRoute(),
                Positioned(
                  child: Container(
                    //height: MediaQuery.of(context).size.height*0.35,
                    margin: EdgeInsets.only(top: ScreenUtil().setWidth(70),left: 20,right: 20),
                    height: ScreenUtil().setHeight(280),
                    child: SvgPicture.string(
                      SvgImg.svgRunlin,
                      height: ScreenUtil().setWidth(344),
                      width: ScreenUtil().setWidth(262),
                    ),
                  ),
                ),
                Container(
                    height: ScreenUtil().setHeight(321),
                    margin: EdgeInsets.only(
                        top: ScreenUtil().setHeight(305),
                        left: ScreenUtil().setWidth(20)),
                    decoration: BoxDecoration(
                        color: Color(0Xffc5daee),
                        borderRadius: BorderRadius.circular(20),
                        boxShadow: [
                          BoxShadow(color: Color(0x99E6EAF0), offset: Offset(5.0, 5.0),
                              blurRadius: 10.0,
                              spreadRadius: 2.0),
                          BoxShadow(
                              color: Color(0x99E6EAF0), offset: Offset(1.0, 1.0)),
                          BoxShadow(color: Color(0x99E6EAF0))
                        ]
                    ),
                    child: Container(
                      height: ScreenUtil().setHeight(321),
                      width: ScreenUtil().setWidth(335),
                      margin: EdgeInsets.only(top: 5),
                      decoration: BoxDecoration(
                        color: Color(0Xffffffff),
                        borderRadius: BorderRadius.circular(20),
                      ),
                      child: Container(
                        child: WillPopScope(
                          child: _bodyWidget(),
                          onWillPop: () async{
                            setState(() {
                              if (_phone == true) _phone = false;
                            });
                            if (_phone == false) {
                              Navigator.pop(context);
                              return true;
                            }
                            return false;
                          },
                        ),
                      ),
                    )),
              ],
            )),
      ),
    );
  }

  /// 主体区域
  Widget _bodyWidget() {
    if (_phone == true) {
      return phoneLogin();
    } else {
      return Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          Container(
            child: Text(
              '從一下方式登入',
              style: TextStyle(
                color: Color(0Xff2D7FC7),
                fontSize: ScreenUtil().setSp(17),
                fontFamily: "SemiBold",
              ),
            ),
          ),
          loginButton(
            color1: Color(0xff93BB24),
            color2: Color(0xff2D7FC7),
            image: "images/phone_icon.png",
            type: "isFilling",
            title: "電話號碼登入",
            onPressed: () => setState(() => _phone = true),
          ),
          loginButton(
            color1: Color(0xff93BB24),
            color2: Color(0xff2D7FC7),
            image: "images/wechat_icon.png",
            type: "isBorder",
            title: "微信登入",
            fontColor: Color(0Xff93BB24),
            onPressed: null,
          ),
          loginButton(
            color1: Color(0xff2D7FC7),
            color2: Color(0xff93BB24),
            image: "images/fb_icon.png",
            type: "isBorder",
            title: "Facebook 登入",
            fontColor: Color(0Xff2D7FC7),
            onPressed: null,
          ),
          Container(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(
                  '還未成為會員？',
                  style: TextStyle(
                      color: Color(0Xff154D7C),
                      fontSize: ScreenUtil().setSp(13),
                      fontFamily: "SemiBold",
                      fontWeight: FontWeight.bold),
                ),
                GestureDetector(
                  onTap: () {},
                  child: Text(
                    '按此註冊',
                    style: TextStyle(
                        color: Color(0Xff93BB24),
                        fontSize: ScreenUtil().setSp(13),
                        fontFamily: "SemiBold",
                        fontWeight: FontWeight.bold),
                  ),
                )
              ],
            ),
          )
        ],
      );
    }
  }

  /// 电话号码登录
  Widget phoneLogin() {
    return Column(
//      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        phoneLoginTitle("驗證電話號碼"),
        LoginTextInputWidget(
          tel: "+853",
          controller: _phoneController,
        ),
        Row(
          children: [
            Expanded(
              child: LoginTextInputWidget(
                controller: _codeController,
              ),
            ),
            FlatButton(
              child: Text(
                _codeCountdownStr,
                style: TextStyle(
                    color: Color(0xffADC044),
                    fontSize: ScreenUtil().setSp(13)),
              ),
              onPressed: () => GetVerificationCode(),
            ),
          ],
        ),
        Container(
          height: 50,
        ),
        loginButton(
            color1: Color(0xff93BB24),
            color2: Color(0xff2D7FC7),
            width: 200,
            image: "images/phone_icon.png",
            type: "isFilling",
            title: "登入",
            onPressed: _login)
      ],
    );
  }

  /// 手机登录标题

  Widget phoneLoginTitle(String title) {
    return Container(
      margin: EdgeInsets.only(top: 15, bottom: 10),
      child: Text(
        title,
        style: TextStyle(
            color: Color(0xff008DCD),
            fontSize: ScreenUtil().setSp(18),
            fontWeight: FontWeight.w400),
      ),
    );
  }

  /*
   * 渐变色 Color color1 color2
   * 标题 String title
   * 点击事件 onPress
   * 图标 Image
   * Type bool isBorder or isFilling
   */
  Widget loginButton(
      {@required Color color1,
        @required Color color2,
        VoidCallback onPressed,
        @required image,
        @required type,
        @required String title,
        num width=273,
        Color fontColor}) {
    return Container(
      width: ScreenUtil().setWidth(width),
      height: ScreenUtil().setHeight(50),
      decoration: BoxDecoration(
          gradient: LinearGradient(colors: [color1, color2]), // 渐变色
          borderRadius: BorderRadius.circular(50)),
      child: Container(
          margin: EdgeInsets.all(2),
          decoration: BoxDecoration(
              color: type == "isFilling" ? Colors.transparent : Colors.white,
              borderRadius: BorderRadius.circular(50)),
          child: FlatButton(
            onPressed: onPressed,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Image.asset(
                  image,
                  height: 22,
                  width: 25,
                ),
                Container(
                  width: 10,
                ),
                Text(
                  title,
                  style: TextStyle(
                    color: fontColor == null ? Colors.white : fontColor,
                    fontSize: ScreenUtil().setSp(16),
                    fontFamily: "SemiBold",
                  ),
                ),
              ],
            ),
          )),
    );
  }
}
